<template>
	<div class="deploy-dialog">
		<el-dialog
			:title="dialogTitle"
			:show-close="false"
			:close-on-click-modal="false"
			:visible.sync="visible"
			width="500px"
			@close="closeHandle"
		>
			<el-form
				label-position="right"
				ref="modelFormRef"
				label-width="105px"
				:model="modelForm"
			>
				<el-form-item
					label="部署类型"
					prop="deployType"
					:rules="{
						required: true,
						message: '请输入部署类型',
						trigger: 'change',
					}"
				>
					<el-select
						v-model="modelForm.deployType"
						placeholder="请选择"
						class="env-select"
						:disabled="dialogType !== 'add' || (dialogType === 'add' && modelForm.tags.length)"
						@change="updateTypeChange"
					>
						<el-option
							v-for="item in deployTypeOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						>
						</el-option>
					</el-select>
				</el-form-item>

				<el-form-item
					label="部署描述"
					prop="info"
					:rules="{
						required: true,
						message: '请输入部署描述',
						trigger: ['blur', 'change'],
					}"
				>
					<el-input
						type="textarea"
						v-model="modelForm.info"
					/>
				</el-form-item>
				<el-card
					v-for="(item, index) in modelForm.tags"
					:key="index"
				>
					<div
						slot="header"
						class="clearfix el-card-title"
					>
						<span>{{ `发包配置${index + 1}` }}</span>
						<i
							class="el-icon-close"
							@click="removeItem(index)"
						></i>
					</div>
					<el-form-item
						:rules="{
							required: true,
							message: '请输入发包tag',
							trigger: ['blur', 'change'],
						}"
						label="发包tag"
						:prop="'tags.' + index + '.tag'"
					>
						<el-input
							v-model="item.tag"
							placeholder="请输入发包tag"
							@input="tagInput($event, index)"
						></el-input>
					</el-form-item>

					<el-form-item
						required
						label="发包service"
						:prop="'tags.' + index + '.services'"
						:rules="[{ validator: validateTree, trigger: 'change' }]"
					>
						<el-tree
							:ref="`tree${index}`"
							:data="treeData"
							show-checkbox
							node-key="id"
							:props="treeProps"
							@check="(data, checked) => handleTreeCheck(index, data, checked)"
						></el-tree>
					</el-form-item>
				</el-card>
				<el-button
					class="deploy-dialog-add-tag"
					type="primary"
					icon="el-icon-plus"
					:disabled="!modelForm.deployType"
					@click="addItem"
					>新增发包配置</el-button
				>
			</el-form>
			<span
				slot="footer"
				class="dialog-footer"
			>
				<el-button @click="dialogHandle('cancel')">取 消</el-button>
				<el-button
					type="primary"
					@click="dialogHandle('confirm')"
					>确 定</el-button
				>
			</span>
		</el-dialog>
	</div>
</template>

<script>
import { piplineDeployGet, piplineTaskGetStageTask } from '@/api/pipeline/pipeline-execution';

export default {
	name: 'deployDialog',
	props: {
		dialogType: {
			type: String,
			default: 'add',
		},
		id: [String, Number],
		deployTypeOptions: {
			type: Array,
			defualt: () => {
				return [];
			},
		},
	},
	computed: {
		dialogTitle() {
			return {
				add: '新增部署',
				edit: '修改部署',
			}[this.dialogType];
		},
	},
	data() {
		return {
			visible: true,
			modelForm: {
				deployType: undefined,
				info: '',
				tags: [],
			},
			parentIds: [],
			treeData: [],
			treeProps: {
				label: 'label',
				children: 'tasks',
			},
		};
	},
	mounted() {
		if (this.id) {
			this.getDeployGet();
		}
	},
	methods: {
		tagInput(e, index) {
			this.modelForm.tags[index].tag = e.replace(/[^0-9]/g, '');
			this.$nextTick();
		},
		closeHandle() {
			this.$emit('closeHandle');
		},
		async getDeployGet() {
			try {
				const { data } = await piplineDeployGet({ id: this.id });

				data.tags = data.tags?.map(item => {
					return {
						tag: item.tag,
						services: item.services?.map(cItem => {
							return cItem.name;
						}),
					};
				});

				this.modelForm = data;

				await this.getStageTask();

				this.$nextTick(() => {
					this.modelForm.tags.forEach((item, index) => {
						this.$refs[`tree${index}`][0].setCheckedKeys(item.services, true);
					});
				});
			} catch (error) {
				this.$message.error(error);
			}
		},
		async getStageTask() {
			try {
				const { data } = await piplineTaskGetStageTask(this.modelForm.deployType);
				this.treeData = data.map(item => {
					const { tasks, ...other } = item;
					const list = tasks.map(cItem => {
						return {
							id: cItem.taskCiName,
							label: cItem.taskCiName,
							...other,
						};
					});
					this.parentIds.push(item.stageCiName);
					return {
						id: item.stageCiName,
						label: item.stageCiName,
						tasks: list,
						...other,
					};
				});
			} catch (error) {
				this.$message.error(error);
			}
		},
		updateTypeChange(type) {
			if (type) {
				this.getStageTask();
			}
		},
		// 树形选择变化
		handleTreeCheck(index, data, checked) {
			this.modelForm.tags[index].services = checked.checkedKeys;
		},
		// 自定义树形组件验证
		validateTree(rule, value, callback) {
			const index = rule.field.split('.')[1];
			if (this.modelForm.tags[index].services.length === 0) {
				callback(new Error('请至少选择一个发包service'));
			} else {
				callback();
			}
		},
		// 添加新项
		addItem() {
			this.modelForm.tags.push({
				tag: '',
				services: [], // 存储选中的树节点
			});
		},
		// 移除项
		removeItem(index) {
			this.modelForm.tags.splice(index, 1);
		},
		dialogHandle(type) {
			switch (type) {
				case 'cancel':
					this.$emit('dialogHandle', type);
					break;
				case 'confirm':
					this.submitForm(type);
					break;
			}
		},
		// 提交表单
		submitForm(type) {
			this.$message.close();
			if (this.modelForm.tags.length > 0) {
				this.$refs.modelFormRef.validate(valid => {
					if (valid) {
						// 表单验证通过，处理提交逻辑
						console.log('表单数据:', this.modelForm);
						let obj = this.modelForm;
						obj.tags.forEach(item => {
							item.services = item.services.filter(cItem => {
								return !this.parentIds.includes(cItem);
							});
						});
						if (this.dialogType !== 'add') {
							obj['id'] = this.id;
						}

						this.$emit('dialogHandle', type, obj);
					} else {
						this.$message.error('请填写完整表单');
						return false;
					}
				});
			} else {
				this.$message.error('请选择发包配置');
			}
		},
	},
};
</script>

<style lang="scss" scoped>
.el-card {
	margin-bottom: 22px;

	.el-icon-close {
		float: right;
		height: 24px;
		line-height: 24px;
		cursor: pointer;
	}

	&-title {
		height: 24px;
		line-height: 24px;
	}

	// :deep(.el-card__body) {
	//   max-height: 200px;
	//   overflow: hidden;
	//   overflow-y: auto;
	// }
}

.env-select {
	width: 100%;
}

.deploy-dialog {
	&-add-tag {
		height: 32px;
		line-height: 32px;
		padding: 0 12px;
	}
}
</style>
